package com.ijtunes;

import com.ijtunes.utils.Property;
import com.ijtunes.utils.Properties;
import com.ijtunes.filetypes.Track;
import com.ijtunes.utils.Logger;
import java.util.logging.Level;

public abstract class OrganisingExpression {
    public static String initExpression = null;
    public static String parsedInitExpression = null;
    
    public static String form(Track track) {
        if(initExpression == null || Properties.hasUpdated(Property.ORGANISING_EXPRESSION, initExpression.hashCode())) {
            initExpression = Properties.get(Property.ORGANISING_EXPRESSION);
            parsedInitExpression = initExpression.replace(OrganisingTag.ROOT.toString(), OrganisingTag.valueOfTag(OrganisingTag.ROOT, track));
        }
        
        String expression = parsedInitExpression;
        int upTo = 0;
        while(upTo < expression.length() - 2 && upTo >= 0) {
            upTo = expression.indexOf('%', upTo);
            if(upTo > 0) {
                int nextPoint = expression.indexOf('%', upTo + 1) + 1;
                CharSequence cs = expression.substring(upTo, nextPoint);
                CharSequence cs2 = OrganisingTag.valueOfTag(OrganisingTag.tagFromString(cs.toString()), track);
                if(cs2 == null) {
                    expression = null;
                    break;
                }

                upTo = upTo + cs2.length() + 1;
                expression = expression.replace(cs, cs2);
            }
        }

        /*try {
        expression = new String(expression.getBytes("ASCII"), "ASCII");
        } catch (UnsupportedEncodingException uee) {
        Logger.log(OrganisingExpression.class.getName(), "Unable to encode track: " + track.getLocation(), uee);
        }*/

        //expression = expression.replaceAll("r'[\"*:<>\\?|]'", "_");

        //expression.replaceAll("r'[^\x00-\x7F]'", RegularExpression)
        return expression;
    }
}
